// pages/user-center/user-center.js
const { get, post } = require('../../utils/api.js')
const { showError, showSuccess, showToast, getStorage } = require('../../utils/util.js')
const { navigateTo } = require('../../utils/router.js')
const { logout } = require('../../utils/auth.js')

Page({
  data: {
    // 用户资料
    userProfile: {
      nickname: '林小雨',
      gender: 'female',
      age: 26,
      height: 165,
      currentCity: '上海',
      education: '硕士',
      occupation: '医生',
      personalStatement: '热爱生活，喜欢旅行和摄影。希望找到一个有趣的灵魂一起探索世界。',
      isOnline: true,
      avatarConfig: {
        faceShape: 'oval',
        hairstyle: 'long_wavy',
        hairColor: 'brown',
        eyeShape: 'almond',
        clothing: {
          category: 'casual',
          item: 'sweater',
          color: 'pink'
        },
        accessories: {
          glasses: 'none',
          hat: 'none',
          jewelry: 'earrings',
          scarf: 'none'
        }
      },
      isRealNameVerified: false,
      isEducationVerified: false,
      isWorkVerified: false,
      isVip: false
    },
    
    // 用户统计
    userStats: {
      likesReceived: 12,
      matchSuccess: 5,
      visitorsCount: 28
    },
    
    // 兴趣爱好
    interests: ['旅行', '摄影', '美食', '瑜伽'],
    
    // 用户统计
    userStats: {
      likesCount: 0,
      matchesCount: 0,
      visitorsCount: 0
    },
    
    // 资料完善度
    profileCompletion: 0,
    
    // 认证状态
    verificationStatus: '未认证',
    
    // 其他数据
    blocklistCount: 0,
    todayVisitors: 0,
    postsCount: 0,
    cacheSize: '0MB',
    appVersion: '1.0.0',
    
    // 加载状态
    loading: false,
    
    // 弹窗状态
    showLogoutDialog: false,
    showClearCacheDialog: false
  },

  onLoad() {
    this.initPage()
  },

  onShow() {
    // 页面显示时刷新数据
    this.loadUserData()
  },

  /**
   * 初始化页面
   */
  initPage() {
    this.loadUserData()
    this.calculateCacheSize()
  },

  /**
   * 加载用户数据
   */
  loadUserData() {
    this.setData({ loading: true })
    
    // 获取用户资料
    const app = getApp()
    const userProfile = app.getUserProfile() || {}
    
    // 并发请求数据
    Promise.all([
      this.loadUserProfile(),
      this.loadUserStats(),
      this.loadUserSettings()
    ]).then(results => {
      const [profile, stats, settings] = results
      
      // 计算资料完善度
      const completion = this.calculateProfileCompletion(profile)
      
      // 计算认证状态
      const verificationStatus = this.getVerificationStatus(profile)
      
      this.setData({
        userProfile: { ...userProfile, ...profile },
        userStats: stats,
        profileCompletion: completion,
        verificationStatus,
        blocklistCount: settings.blocklistCount || 0,
        todayVisitors: settings.todayVisitors || 0,
        postsCount: settings.postsCount || 0,
        loading: false
      })
    }).catch(error => {
      console.error('加载用户数据失败:', error)
      this.setData({ loading: false })
    })
  },

  /**
   * 加载用户资料
   */
  loadUserProfile() {
    return get('/api/user/profile')
      .catch(error => {
        console.error('加载用户资料失败:', error)
        return {}
      })
  },

  /**
   * 加载用户统计
   */
  loadUserStats() {
    return get('/api/user/stats')
      .catch(error => {
        console.error('加载用户统计失败:', error)
        return {
          likesCount: 0,
          matchesCount: 0,
          visitorsCount: 0
        }
      })
  },

  /**
   * 加载用户设置
   */
  loadUserSettings() {
    return get('/api/user/settings')
      .catch(error => {
        console.error('加载用户设置失败:', error)
        return {}
      })
  },

  /**
   * 计算资料完善度
   */
  calculateProfileCompletion(profile) {
    const fields = [
      'nickname', 'gender', 'birthday', 'height', 'currentCity',
      'education', 'occupation', 'personalStatement', 'avatarConfig'
    ]
    
    const completedFields = fields.filter(field => {
      const value = profile[field]
      return value !== null && value !== undefined && value !== ''
    })
    
    return Math.round((completedFields.length / fields.length) * 100)
  },

  /**
   * 获取认证状态
   */
  getVerificationStatus(profile) {
    const verifications = [
      profile.isRealNameVerified,
      profile.isEducationVerified,
      profile.isWorkVerified
    ]
    
    const verifiedCount = verifications.filter(v => v).length
    
    if (verifiedCount === 0) return '未认证'
    if (verifiedCount === 3) return '全部认证'
    return `${verifiedCount}/3项已认证`
  },

  /**
   * 计算缓存大小
   */
  calculateCacheSize() {
    try {
      wx.getStorageInfo({
        success: (res) => {
          const size = (res.currentSize / 1024).toFixed(2) + 'MB'
          this.setData({ cacheSize: size })
        }
      })
    } catch (error) {
      console.error('获取缓存大小失败:', error)
    }
  },

  /**
   * 编辑头像
   */
  editAvatar() {
    navigateTo('/pages/avatar/avatar?edit=true')
  },

  /**
   * 编辑资料
   */
  editProfile() {
    navigateTo('/pages/profile/profile')
  },

  /**
   * 编辑匹配偏好
   */
  editMatchPreferences() {
    navigateTo('/pages/match-preferences/match-preferences')
  },

  /**
   * 管理身份认证
   */
  manageVerification() {
    navigateTo('/pages/verification/verification')
  },

  /**
   * 管理隐私设置
   */
  managePrivacy() {
    navigateTo('/pages/privacy-settings/privacy-settings')
  },

  /**
   * 管理黑名单
   */
  manageBlocklist() {
    navigateTo('/pages/blocklist/blocklist')
  },

  /**
   * 管理账号安全
   */
  manageSecurity() {
    navigateTo('/pages/security/security')
  },

  /**
   * 查看访客
   */
  viewVisitors() {
    navigateTo('/pages/visitors/visitors')
  },

  /**
   * 查看点赞记录
   */
  viewLikeHistory() {
    navigateTo('/pages/like-history/like-history')
  },

  /**
   * 查看我的动态
   */
  viewMyPosts() {
    navigateTo('/pages/my-posts/my-posts')
  },

  /**
   * 管理通知设置
   */
  manageNotifications() {
    navigateTo('/pages/notifications/notifications')
  },

  /**
   * 更改语言
   */
  changeLanguage() {
    wx.showActionSheet({
      itemList: ['简体中文', 'English'],
      success: (res) => {
        const languages = ['zh-CN', 'en-US']
        const selectedLang = languages[res.tapIndex]
        
        // TODO: 实现语言切换
        showToast('语言切换功能开发中')
      }
    })
  },

  /**
   * 显示清理缓存确认弹窗
   */
  clearCache() {
    this.setData({ showClearCacheDialog: true })
  },

  /**
   * 确认清理缓存
   */
  confirmClearCache() {
    wx.clearStorage({
      success: () => {
        this.setData({
          cacheSize: '0MB',
          showClearCacheDialog: false
        })
        showSuccess('缓存已清理')
      },
      fail: (error) => {
        console.error('清理缓存失败:', error)
        showError('清理失败，请重试')
      }
    })
  },

  /**
   * 取消清理缓存
   */
  cancelClearCache() {
    this.setData({ showClearCacheDialog: false })
  },

  /**
   * 查看用户指南
   */
  viewGuide() {
    navigateTo('/pages/guide/guide')
  },

  /**
   * 意见反馈
   */
  giveFeedback() {
    navigateTo('/pages/feedback/feedback')
  },

  /**
   * 联系客服
   */
  contactSupport() {
    wx.makePhoneCall({
      phoneNumber: '400-123-4567',
      fail: () => {
        wx.setClipboardData({
          data: '400-123-4567',
          success: () => {
            showToast('客服电话已复制到剪贴板')
          }
        })
      }
    })
  },

  /**
   * 关于应用
   */
  aboutApp() {
    navigateTo('/pages/about/about')
  },

  /**
   * 升级VIP
   */
  upgradeVip() {
    navigateTo('/pages/vip/vip')
  },

  /**
   * 完善资料
   */
  completeProfile() {
    this.editProfile()
  },

  /**
   * 查看获赞
   */
  viewLikes() {
    navigateTo('/pages/like-history/like-history')
  },

  /**
   * 查看匹配
   */
  viewMatches() {
    wx.switchTab({
      url: '/pages/matches/matches'
    })
  },

  /**
   * 显示退出登录确认弹窗
   */
  showLogoutDialog() {
    this.setData({ showLogoutDialog: true })
  },

  /**
   * 确认退出登录
   */
  confirmLogout() {
    this.setData({ showLogoutDialog: false })
    logout()
  },

  /**
   * 取消退出登录
   */
  cancelLogout() {
    this.setData({ showLogoutDialog: false })
  },

  /**
   * 分享页面
   */
  onShareAppMessage() {
    return {
      title: '青鸟笺 - 用心灵相遇，让真爱绽放',
      path: '/pages/discovery/discovery',
      imageUrl: '../../images/share-app.png'
    }
  }
})